﻿Imports Global_Visas_Business_Layer
Imports System.ComponentModel
Imports Word
Imports Telerik.Windows.Controls
Imports Telerik.Windows.Controls.GridView
Imports Telerik.Windows.Data
Imports System.Data
Imports System.Text
Imports System.Reflection
Imports System.Windows.Automation.Peers
Imports System.Windows.Automation.Provider
Imports Microsoft.Windows.Themes
Imports CommonDialog

Partial Public Class frmCRMMainForm
    Public Event ShowDisplayForm(ByVal userControlName As String)
    Public Event ShowDynamicTab(ByVal userControlName As String)
    Dim frm_MenuLayout As Integer
    Dim objDTGrid As DataTable
    Dim StrFieldNames() As String
    Private currentConName As String
    Private checkLoad As Boolean = False
    Private blnForceLoadGrid As Boolean = False
    Dim firstLoad As Boolean = True

    Public Enum CaseStatus
        PreSale = 1
        Initiated = 2
        All = 3
    End Enum

    Public Enum ConRole
        SalesCon = 1
        CaseWorker = 2
        Either = 3
        CaseCoordinator = 4
    End Enum

    Public Enum OnHold
        Exclude = 1
        Include = 2
        Only = 3
    End Enum

    Private ReadOnly Property StatusOnHold() As OnHold
        Get
            If Me.radHoldExclude.IsChecked Then
                Return OnHold.Exclude
            ElseIf Me.radHoldInclude.IsChecked Then
                Return OnHold.Include
            ElseIf Me.radHoldOnly.IsChecked Then
                Return OnHold.Only
            End If
        End Get
    End Property

    Private ReadOnly Property StatusCaseStatus() As CaseStatus
        Get
            If Me.radViewPreSale.IsChecked Then
                Return CaseStatus.PreSale
            ElseIf Me.radViewInitiated.IsChecked Then
                Return CaseStatus.Initiated
            ElseIf Me.radViewAll.IsChecked Then
                Return CaseStatus.All
            End If
        End Get
    End Property

    Private ReadOnly Property StatusConRole() As ConRole
        Get
            If Me.radRoleCW.IsChecked Then
                Return ConRole.CaseWorker
            ElseIf Me.radRoleEither.IsChecked Then
                Return ConRole.Either
            ElseIf Me.radRoleSales.IsChecked Then
                Return ConRole.SalesCon
            ElseIf Me.radRoleCaseCoordinator.IsChecked Then
                Return ConRole.CaseCoordinator
            End If
        End Get
    End Property


    Private Sub btnGoTo_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnGoTo.Click
        Try
            Me.DoSearch()
        Catch ex As Exception
        Finally
        End Try

    End Sub

    Private Sub DoSearch()

        Dim progressBar As frmProgressBar = Nothing
        ' open frmMainDisplay for selected event
        Dim test As Singleton = Singleton.Instance
        Try
            progressBar = New frmProgressBar()
            progressBar.TextToDisplay = "Dear " & test.CurrentConName & ", please wait while CRM loads ....."
            progressBar.Show()

            Dim lngSearchID As Long
            Dim strSearchResult As String
            Dim strName As String = String.Empty
            If Not IsNumeric(Me.txtSearch.Text) Then

                If radSearchCase.IsChecked Then strName = radSearchCase.Content.ToString
                If radSearchCompany.IsChecked Then strName = radSearchCompany.Content.ToString
                If radSearchPerson.IsChecked Then strName = radSearchPerson.Content.ToString
                If radSearchInvoice.IsChecked Then strName = radSearchInvoice.Content.ToString
                CommonFuncs.DisplayMessage("Please enter ID of the " & strName & ".", CustomDialogIcons.Information, "Search")
                Exit Sub
            Else
                lngSearchID = Me.txtSearch.Text
            End If

            If Me.radSearchCase.IsChecked Then
                ' Case search
                GlobalCRM.CurrentSearchType = GlobalCRM.enuSearchType.eCase
                GlobalCRM.TabSelection = GlobalCRM.enumSelectTab.eCase
            ElseIf Me.radSearchCompany.IsChecked Then
                ' Company search
                GlobalCRM.CurrentSearchType = GlobalCRM.enuSearchType.eCompany
                GlobalCRM.TabSelection = GlobalCRM.enumSelectTab.eCompany
            ElseIf Me.radSearchPerson.IsChecked Then
                ' Person search
                GlobalCRM.CurrentSearchType = GlobalCRM.enuSearchType.ePerson
                GlobalCRM.TabSelection = GlobalCRM.enumSelectTab.ePerson
            ElseIf Me.radSearchInvoice.IsChecked Then
                ' Invoice search
                GlobalCRM.CurrentSearchType = GlobalCRM.enuSearchType.eInvoice
                GlobalCRM.TabSelection = GlobalCRM.enumSelectTab.eAccount
            End If

            ' run the search
            strSearchResult = CommonDataFunctions.IDSearch(lngSearchID, GlobalCRM.CurrentSearchType)
            If strSearchResult = "ok" Then
                'Load frmMaindisplay

                'mainDisplayForms.ShowDialog()
                'Krishan Kumar K

                frmCRMMainDisplay.loadTabCases = False
                frmCRMMainDisplay.loadTabAccounts = False
                frmCRMMainDisplay.loadTabPeople = False
                frmCRMMainDisplay.loadTabCompany = False
                frmCRMMainDisplay.loadTabDocs = False
                frmCRMMainDisplay.loadTabEvent = False

                RaiseEvent ShowDynamicTab("maindisplay")
                'Sumathi Vinayak S
                'Dim crm As New frmCRMMDI1
                'crm.CreateDynamicTab() 
            Else
                CommonFuncs.DisplayMessage(strSearchResult, CustomDialogIcons.Information, "Go To")
            End If

        Catch ex As Exception
        Finally
            progressBar.Close()
        End Try
    End Sub

    Private Sub gvlogo_ImageFailed(ByVal sender As System.Object, ByVal e As System.Windows.ExceptionRoutedEventArgs)
        Dim dlg As Microsoft.Win32.OpenFileDialog = New Microsoft.Win32.OpenFileDialog()
        Dim result As Boolean = dlg.ShowDialog()
        If result = True Then
            'gvlogo.Source = New BitmapImage(New Uri(dlg.FileName))
        Else
            'gvlogo.Source = New BitmapImage(New Uri("\\constellation\e\it\Deployment\GVLogo\visa_logo.jpg"))
        End If
    End Sub

    Private Sub btnConname_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnConName.Click
        Dim consultantdataView As DataView = Nothing
        Dim consultantdata As DataTable = Nothing
        Try
            Dim progressBar As New frmProgressBar()
            progressBar.TextToDisplay = "Dear " & GlobalCRM.CurrentConName & " , Please wait while CRM reload your cases ...."
            progressBar.Show()
            Me.currentConName = "once"
            Me.drpBranch.SelectedValue = CommonDataFunctions.GetLoggedOnConsultantBranchID()
            Me.drpDepts.Text = CommonDataFunctions.GetDepartmentName
            consultantdataView = CType(Me.drpCons.ItemsSource, DataView)
            consultantdata = consultantdataView.Table
            For currentRowIndex As Integer = 0 To consultantdata.Rows.Count - 1
                Dim currentRow As DataRow = consultantdata.Rows(currentRowIndex)
                If currentRow(0) = GlobalCRM.CurrentConID Then
                    drpCons.SelectedIndex = currentRowIndex
                End If
            Next
            'Me.drpCons.SelectedValue = GlobalCRM.CurrentConID
            progressBar.Close()
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmCRMMainFrame-btnConName_Click", False)
        End Try

    End Sub


    Private Sub frmCRMMainForm_GotFocus(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.GotFocus

        firstLoad = False

    End Sub

    


    Private Sub frmCRMMainForm_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded

        'WpfMessageBox.Show("You have clicked on Error Message", "Error . . .", WpfMessageBoxButton.OK, WpfMessageBoxImage.Error)

        If checkLoad = True Then
            LoadGrid()
            Exit Sub
        Else
            firstLoad = True
        End If


        GeneralTasks.ChangeTheme(Me)
        GeneralTasks.EnumerateandFill(Me.LogicalChildren)
        Me.cmbStyle.Text = My.Settings.CurrentTheme
        'Me.cmbColor.Text = My.Settings.CurrentColor
        Me.SelectColor()


        Dim eventArguments As EventArgs
        Try

            Dim isActive As Long = 1
            Dim CRMAccess As Long = 0
            Me.lblUser.Content = CommonDataFunctions.GetConsultantNameNT

            'Me.lblUser.Content = String.Empty
            'If GlobalCRM.CurrentNTUserName = String.Empty Then
            '    checkLoad = True
            '    frmLogin = New frmLogin
            '    frmLogin.ShowDialog()
            '    If GlobalCRM.CurrentNTUserName = String.Empty Then
            '        CommonFuncs.DisplayMessage("The login credentials are incorrect. Please contact IT. " & vbCrLf & "Contact your manager for more details.", CustomDialogIcons.Information, "")
            '        End
            '    Else
            '        Me.lblUser.Content = CommonDataFunctions.GetConsultantNameNT(True)
            '    End If
            'Else
            '    'GlobalCRM.CurrentNTUserName = Me.lblUser.Content
            'End If
            'If GlobalCRM.CurrentNTUserName = String.Empty Then
            '    CommonFuncs.DisplayMessage("The user has not been set up in the system. Please contact the administrator.", CustomDialogIcons.Information, "User Not Set up")
            '    End
            'Else
            '    GlobalCRM.CurrentNTPassword = CommonDataFunctions.GetUserNTPassword(GlobalCRM.CurrentNTUserName)
            'End If
            'isActive = CommonDataFunctions.GetConsultantStatus(GlobalCRM.CurrentNTUserName)

            'If isActive = 0 Then
            '    CommonFuncs.DisplayMessage("The user is inactive in the system. Please activate the CRM and try again. " & vbCrLf & "Contact your manager for more details.", CustomDialogIcons.Information, "")
            '    End
            'End If

            'CRMAccess = CommonDataFunctions.GetConsultantCRMStatus(GlobalCRM.CurrentNTUserName)

            'If CRMAccess = 0 Then
            '    CommonFuncs.DisplayMessage("The CRM has been deactivated for your login. Please contact IT. " & vbCrLf & "Contact your manager for more details.", CustomDialogIcons.Information, "")
            '    End
            'ElseIf CRMAccess = 1 Then
            '    CommonFuncs.DisplayMessage("You just has CRM v2 access. Please contact IT. " & vbCrLf & "Contact your manager for more details.", CustomDialogIcons.Information, "")
            '    End
            'ElseIf CRMAccess = 2 Or CRMAccess = 3 Then
            '    'CommonFuncs.DisplayMessage("You just has CRM v2 access. Please contact IT. " & vbCrLf & "Contact your manager for more details.", CustomDialogIcons.Information, "")
            '    'End
            'End If
            Security.GetUserLevel()
            Dim _ConBranchID As Integer = CommonDataFunctions.GetLoggedOnConsultantBranchID
            Dim _ConDeptID As Integer = CommonDataFunctions.GetLoggedOnConsultantDeptID(GlobalCRM.CurrentConName.Trim)
            'Dim _ConDeptID As Integer = CommonDataFunctions.GetLoggedOnConsultantDeptID("test")



            With Me.drpBranch
                .SelectedValuePath = "Branch_ID"
                .DisplayMemberPath = "Branch_Name"
                .ItemsSource = CType(CommonDataFunctions.BranchList, IListSource).GetList
                .SelectedValue = _ConBranchID
            End With

            With Me.drpDepts
                .SelectedValuePath = "Department_ID"
                .DisplayMemberPath = "Department_Name"
                .ItemsSource = CType(CommonDataFunctions.DepartmentList(Me.drpBranch.SelectedValue), IListSource).GetList
                .SelectedValue = _ConDeptID
            End With
            With Me.drpCons
                .SelectedValuePath = "con_id"
                .DisplayMemberPath = "con_name"
                .ItemsSource = CType(CommonDataFunctions.ConsultantList(True, drpDepts.SelectedValue), IListSource).GetList
            End With
            Me.LoadCurrentValues()
            'drpView.SelectedIndex = 0
            Me.btnConName.Content = Me.lblUser.Content
            Select Case Security._SecurityLevel
                Case SecurityLevel.NormalUser
                    btnAdmin.Visibility = System.Windows.Visibility.Hidden
                    drpCons.IsEnabled = False
                    drpBranch.IsEnabled = False
                    drpDepts.IsEnabled = False
                    btnConName.Visibility = System.Windows.Visibility.Hidden
                    btnAllocation.Visibility = System.Windows.Visibility.Hidden
                Case SecurityLevel.BranchManager
                    drpBranch.IsEnabled = False
                    btnAdmin.Visibility = System.Windows.Visibility.Hidden
                    drpCons.IsEnabled = True
                    drpDepts.IsEnabled = True
                    btnConName.Visibility = System.Windows.Visibility.Visible
                    btnAllocation.Visibility = System.Windows.Visibility.Visible
                Case SecurityLevel.AdminUser
                    btnAdmin.Visibility = System.Windows.Visibility.Visible
                    drpCons.IsEnabled = True
                    drpBranch.IsEnabled = True
                    drpDepts.IsEnabled = True
                    btnConName.Visibility = System.Windows.Visibility.Visible
                    btnAllocation.Visibility = System.Windows.Visibility.Visible
            End Select

            Me.drpTaskView.SelectedIndex = 0

            'Me.drpView.SelectedIndex = 0
            Me.drpDepts.Text = CommonDataFunctions.GetDepartmentName
            Me.drpCons.Text = Me.lblUser.Content
            GlobalCRM.CurrentConID = Me.drpCons.SelectedValue
            'Try
            '    eventArguments = New EventArgs
            '    eventArguments = CType(eventArguments, System.Windows.Controls.SelectionChangedEventArgs)
            '    drpCons_SelectionChanged(Nothing, eventArguments)

            'Catch ex As Exception

            'End Try
            If CommonFuncs.GetDBConnectionString.ToLower.IndexOf("constellation") > 0 Then
                Me.Background = New SolidColorBrush((Colors.Cyan))
            End If

            If drpDepts.Items.Count = 0 Then
                drpCons.ItemsSource = Nothing
                drpCons.Items.Clear()
            End If

            If cmbColor.Items.Count = 0 Then
                cmbColor.ItemsSource = Nothing
                cmbColor.Items.Clear()
            End If

            GlobalCRM.RefreshSetting = CommonDataFunctions.Usersetting(1, GlobalCRM.CurrentConID)
            GeneralTasks.FillComboBoxWithSystemColorList(cmbColor)


            If CommonDataFunctions.LogInUser(GlobalCRM.CurrentConID) = True Then

            End If
            'StatusStrip1.Items(0).content = "Pipline Details for " & CommonDataFunctions.GetConsultantName(GlobalCRM.CurrentConViewID) & " " & CommonDataFunctions.GetPipeline(GlobalCRM.CurrentConViewID)
            'statPipeline.Text = "Pipline Details for " & CommonSQL.GetConsultantName(value) & " " & CommonSQL.GetPipeline(value)
            'check whether the user has latest version
            'Dim strVersion As String = CommonFunc.LatestVersionRolledOut.Trim
            'If strVersion <> Application.ProductVersion.Trim Then
            '    If MsgBox("Latest version of CRM v" & strVersion & " is available now. " & vbCrLf & "If you would like to install the latest version, please push the button 'Yes'." & vbCrLf & vbCrLf & "All the other programs remain unaffected.", MsgBoxStyle.YesNo, "Latest Version") = MsgBoxResult.Yes Then
            '        'frmMDIMain.InstallLatstVersionToolStripMenuItem_Click(sender, e)
            '        System.Diagnostics.Process.Start("C:\Database\CRMInstallation.Bat")
            '        End
            '        'btnExit_Click(sender, e)
            '    Else
            '    End If
            'End If
            'Me.RefreshLists()


            'Dim strVersion As String = CommonDataFunctions.LatestVersionRolledOut.Trim
            'Dim strInstallationPath As String
            'If strVersion <> My.Application.Info.Version.ToString Then
            '    If CommonFuncs.DisplayyesNoMessage("Latest version of CRM v" & strVersion & " is available now. " & vbCrLf & "If you would like to install the latest version, please push the button 'Yes'." & vbCrLf & vbCrLf & "All the other programs remain unaffected.", CustomDialogIcons.Question, "Latest Version Available") = 1 Then
            '        'frmMDIMain.InstallLatstVersionToolStripMenuItem_Click(sender, e)
            '        strInstallationPath = CommonDataFunctions.GetBranchInstallationPath()
            '        If strInstallationPath <> String.Empty Then
            '            System.Diagnostics.Process.Start(strInstallationPath)
            '            End
            '        Else
            '            CommonFuncs.DisplayMessage("The Branch installation path is not confugured. please contact IT", CommonDialog.CustomDialogIcons.Information, "Installation")
            '        End If
            '    End If
            'End If
            Dim blnFindH As Boolean = False
            For Each Drive As System.IO.DriveInfo In My.Computer.FileSystem.Drives
                If Drive.ToString = "H:\" Then
                    blnFindH = True
                    Exit For
                End If
            Next
            If blnFindH = False Then
                'map h: to local drive
                'If CommonFuncs.CreateDIR("c:\database\" & GlobalCRM.CurrentNTUserName) = True Then
                '    CommonFuncs.commandlinedrives("subst H: c:\database\" & GlobalCRM.CurrentNTUserName)
                If CommonFuncs.CreateDIR("c:\database\" & "test") = True Then
                    CommonFuncs.commandlinedrives("subst H: c:\database\" & "test")
                End If
            End If
            LoadGrid()
            'stsPipeline.= "Pipline Details for " & CommonSQL.GetConsultantName(value) & " " & CommonSQL.GetPipeline(value)
            checkLoad = True
        Catch ex As Exception
        Finally
            eventArguments = Nothing
            Me.txtSearch.Focus()
        End Try

    End Sub

    Private Sub SelectColor()
        For currentItemIndex As Integer = 0 To cmbColor.Items.Count - 1
            Dim item As DataRowView = cmbColor.Items(currentItemIndex)
            If item.Row(0).Equals(My.Settings.CurrentColor) Then
                Me.cmbColor.SelectedIndex = currentItemIndex
            End If
        Next
    End Sub


    Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnExit.Click
        Try
            If CommonFuncs.DisplayyesNoMessage("Are you sure to exit CRM?", CustomDialogIcons.Question, "Close CRM") = 1 Then
                Dim WriteLog As New WriteLog
                WriteLog.WriteToEventLog("CRM Application exited", , EventLogEntryType.Information)
                End
            Else
                Exit Sub
            End If
        Catch ex As Exception
        Finally
            'End
        End Try
    End Sub

    Private Sub drpDepts_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles drpDepts.SelectionChanged
        Try

            With Me.drpCons
                .ItemsSource = Nothing
                .Items.Clear()
                .SelectedValuePath = "con_id"
                .DisplayMemberPath = "con_name"
                Dim departMentId As Integer
                If drpDepts.Text <> String.Empty Then
                    If (drpDepts.SelectedValue <> Nothing) Then
                        departMentId = Convert.ToInt32(drpDepts.SelectedValue.ToString())
                    End If
                End If
                If (departMentId > 0) Then
                    .ItemsSource = CType(CommonDataFunctions.ConsultantList(True, drpDepts.SelectedItem.row.itemarray(0), , Me.drpBranch.SelectedValue), IListSource).GetList
                Else
                    .ItemsSource = CType(CommonDataFunctions.ConsultantsList, IListSource).GetList
                End If
                .SelectedIndex = -1
            End With

            If drpDepts.Items.Count = 0 Then
                drpCons.ItemsSource = Nothing
                drpCons.Items.Clear()
            End If


        Catch ex As Exception
        End Try
    End Sub

    Private Function TaskViewEnd() As Date
        ' convert TaskView selection into a date
        Dim selectedDate As String = String.Empty
        selectedDate = CType((drpTaskView.SelectedItem), ComboBoxItem).Content
        Try
            If selectedDate.ToLower.Contains("today") Or selectedDate = String.Empty Then
                Return Format(Now, "dd-MMM-yyyy") & " 23:59:59"
            ElseIf selectedDate.ToLower.Contains("tomorrow") Then
                Return Format(Now.AddDays(1), "dd-MMM-yyyy") & " 23:59:59"
            ElseIf selectedDate.ToLower.Contains("week") Then
                Return Format(Now.AddDays(7), "dd-MMM-yyyy") & " 23:59:59"
            ElseIf selectedDate.ToLower.Contains("month") Then
                Return Format(Now.AddMonths(1), "dd-MMM-yyyy") & " 23:59:59"
            ElseIf selectedDate.ToLower.Contains("all") Then
                Return Format(Now.AddYears(10), "dd-MMM-yyyy") & " 23:59:59"
            End If
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmMainForm.TaskViewEnd", False)
        End Try

    End Function

    Private Sub drpCons_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles drpCons.SelectionChanged
        Dim progressBar As frmProgressBar = Nothing
        If sender Is Nothing Then
            Exit Sub
        End If
        'Me.Cursor = Cursors.Wait
        ProgressBar = New frmProgressBar()
        progressBar.TextToDisplay = "Dear " & GlobalCRM.CurrentConName & ", please wait while CRM loads the data"
        ProgressBar.Show()
        ' respond to Consultant selection in drop down list
        Dim events As New Global_Visas_Business_Layer.TasksEvents()
        Me.txtMessage.Text = String.Empty

        Try
            Me.Cursor = Cursors.Wait

            ' populate Task listview for current consultant
            Dim itemTable As DataTable
            If Not Me.drpCons.SelectedValue Is Nothing Then
                'Me.btnConName.Content = drpCons.SelectedItem.row.itemarray(1)
                itemTable = CommonDataFunctions.GetSQLDatatable(EventList(Me.drpCons.SelectedValue, Me.TaskViewEnd))
                Dim convertedItems As DataTable = Me.FilterTaskRowsAndReturnDistinctValues(itemTable)


                'DataBinding.BindListView(itemTable, Me.lvwEventsOutstanding)
                lvwEventsOutstanding.ItemsSource = convertedItems
                lvwEventsOutstanding.Columns(0).IsVisible = False
                lvwEventsOutstanding.Columns(5).IsVisible = False
                lvwEventsOutstanding.Columns(6).IsVisible = False
                lvwEventsOutstanding.Columns("Event_DTScheduled").IsVisible = False
                lvwEventsOutstanding.Columns("Event_VIP").IsVisible = False
                lvwEventsOutstanding.Columns(1).Width = New GridLength(150)
                lvwEventsOutstanding.Columns(2).Width = New GridLength(120)
                lvwEventsOutstanding.Columns(3).Width = New GridLength(195)
                lvwEventsOutstanding.Columns(4).Width = New GridLength(195)

                ' populate Cases datagrid for selected consultant
                objDTGrid = CommonDataFunctions.GetSQLDatatable(Me.SQL_Caselist)
                ' Automate the task for cases more than 90 days old
                If sender Is Nothing And Not objDTGrid Is Nothing Then
                    If objDTGrid.Rows.Count > 0 Then
                        Dim i As Integer
                        For i = 0 To objDTGrid.Rows.Count - 1
                            Dim sql As New StringBuilder
                            sql.Append("select case_statusid,case_dtstatus from D_case where case_id = " & objDTGrid.Rows(i).Item("Col_1"))
                            Dim dt As DataTable = CommonDataFunctions.GetSQLDatatable(sql.ToString)
                            If Not dt Is Nothing Then
                                If dt.Rows.Count > 0 Then
                                    If dt.Rows(0).Item("case_statusid") >= 100 And dt.Rows(0).Item("case_dtstatus").ToString <> "" Then
                                        Dim dtToCheck As Date = dt.Rows(0).Item("case_dtstatus")
                                        'If System.DateTime.Today > dtToCheck.AddDays(GlobalCRM.DaysOld) Then
                                        If CommonDataFunctions.GetLocalServer > dtToCheck.AddDays(GlobalCRM.DaysOld) Then
                                            'add an event

                                            events.GblFunc_Add_Event("Collect Payment from Client ", "The case is over " & GlobalCRM.DaysOld & " days old." & vbCrLf & "Please chase the client for Payment", TasksEvents.EventStatus.Task, objDTGrid.Rows(i).Item("Col_1"), TasksEvents.EventTypes.EventCase, 0, 0, GlobalCRM.CurrentConID, Format(Now, "dd-MMM-yyyy"), 1)
                                        End If
                                    End If
                                End If
                            End If
                        Next
                    End If
                End If



                Dim dtt As DataTable = FilterRowsAndReturnDistinctValues(objDTGrid)
                Me.grdCases.ItemsSource = dtt
                Me.grdCases.Columns(2).Width = New GridLength(130)

                ' set global variable for current consultant you are viewing info for
                GlobalCRM.CurrentConViewID = Me.drpCons.SelectedValue
                If GlobalCRM.CurrentConViewID > 0 Then
                    stsPipeline.Items(0).content = "Pipline Details for " & CommonDataFunctions.GetConsultantName(GlobalCRM.CurrentConViewID) & " " & CommonDataFunctions.GetPipeline(GlobalCRM.CurrentConViewID)
                End If
            End If
            Me.Cursor = Cursors.Arrow
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmMainForm.drpCons.SelectedIndexChanged", False)
        Finally
            events = Nothing
            progressBar.Close()
            progressBar = Nothing
        End Try
    End Sub

    Public Sub GetColumns()

        'Dim intTitle As Integer
        'Dim strField As String

        'If objDTGrid Is Nothing Then Exit Sub

        'Try
        '    With Me.grdCases
        '        .Columns(0).Header = "Case ID"


        '        For intTitle = 1 To objDTGrid.Columns.Count - 1
        '            strField = .Columns(intTitle).Header
        '            .Columns(intTitle).Header = StrFieldNames(intTitle)
        '        Next
        '    End With
        'Catch ex As Exception
        '    '  CommonFunc.ErrorHandler(ex, "frmMainForm.GetColumns", False)
        'End Try

    End Sub

    Private Sub drpTaskView_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles drpTaskView.SelectionChanged
        If firstLoad = True Then
            Exit Sub
        End If
        Try
            Me.RefreshLists()
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmCRMMainForm.drpTaskView_SelectionChanged", False)
        End Try
    End Sub

    Public Sub RefreshLists()
        If firstLoad = True Then
            Exit Sub
        End If
        Try

            Dim itemTable As System.Data.DataTable
            Dim taskDate As Date = Me.TaskViewEnd()
            itemTable = CommonDataFunctions.GetSQLDatatable(EventList(Me.drpCons.SelectedValue, taskDate))
            Dim dt As DataTable = Me.FilterTaskRowsAndReturnDistinctValues(itemTable)
            'DataBinding.BindListView(itemTable, Me.lvwEventsOutstanding)            
            lvwEventsOutstanding.ItemsSource = dt
            lvwEventsOutstanding.Columns(0).IsVisible = False
            lvwEventsOutstanding.Columns(5).IsVisible = False
            lvwEventsOutstanding.Columns(6).IsVisible = False
            lvwEventsOutstanding.Columns("Event_DTScheduled").IsVisible = False
            lvwEventsOutstanding.Columns("Event_VIP").IsVisible = False
            lvwEventsOutstanding.Columns(1).Width = New GridLength(150)
            lvwEventsOutstanding.Columns(2).Width = New GridLength(120)
            lvwEventsOutstanding.Columns(3).Width = New GridLength(195)
            lvwEventsOutstanding.Columns(4).Width = New GridLength(195)

            Me.txtMessage.Text = String.Empty
            Me.btnDismissTask.IsEnabled = False
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmMainForm.RefreshLists", False)
        End Try

    End Sub

    Private Sub RefreshOutStandingTaksForLoggedConsultant()
        If firstLoad = True Then
            Exit Sub
        End If
        Try
            Dim itemTable As System.Data.DataTable
            Dim taskDate As Date = Me.TaskViewEnd()
            itemTable = CommonDataFunctions.GetSQLDatatable(EventList(GlobalCRM.CurrentConID, taskDate))
            Dim dt As DataTable = Me.FilterTaskRowsAndReturnDistinctValues(itemTable)
            Dim pipleLineDetailsForConsultant As String = String.Empty
            If (dt.Rows.Count > 0) Then
                pipleLineDetailsForConsultant = "Outstanding Tasks for " & CommonDataFunctions.GetConsultantName(GlobalCRM.CurrentConID) & " are : " & dt.Rows.Count.ToString()
            Else
                pipleLineDetailsForConsultant = "There are no outstanding tasks for " & CommonDataFunctions.GetConsultantName(GlobalCRM.CurrentConID)
            End If
            
            CommonFuncs.DisplayMessageWithoutCaseId(pipleLineDetailsForConsultant, CustomDialogIcons.Information, "CRM")

        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmMainForm.RefreshLists", False)
        End Try

    End Sub
    Public Sub refreshGrid()
        If GlobalCRM.CurrentConID > 0 Then
            Dim sql As String = Me.SQL_Caselist
            objDTGrid = CommonDataFunctions.GetSQLDatatable(sql)
            Dim dtt As DataTable = FilterRowsAndReturnDistinctValues(objDTGrid)
            Me.grdCases.ItemsSource = dtt
            Me.GetColumns()
        End If
    End Sub
    Public Sub LoadGrid()

        If firstLoad = True Or GlobalCRM.RefreshSetting = 1 Then
            If blnForceLoadGrid = False Then
                Exit Sub
            Else
                blnForceLoadGrid = False
            End If
        End If
        Dim singleObject As Singleton = Singleton.Instance
        If singleObject.CurrentConId > 0 Then
            Dim sql As String = Me.SQL_Caselist
            objDTGrid = CommonDataFunctions.GetSQLDatatable(sql)
            Dim dtt As DataTable = FilterRowsAndReturnDistinctValues(objDTGrid)
            Me.grdCases.ItemsSource = dtt
            Me.GetColumns()
        End If
        
        ' 'Me.grdCases.Columns(2).Width = New GridLength(130)
    End Sub

    Public Function FilterRowsAndReturnDistinctValues(ByVal dt As DataTable) As DataTable
        Dim dtt As DataTable = dt.Clone()
        Dim currentCaseId As String = String.Empty
        Dim nextCaseId As String = String.Empty
        Dim lastCaseIdSuccessfullyCopied As String = String.Empty
        Dim currentCaseIndex As Integer
        Dim nextCaseIndex As Integer
        For index As Integer = 0 To dt.Rows.Count - 1
            currentCaseIndex = index
            If (index < dt.Rows.Count - 1) Then
                nextCaseIndex = index + 1
            Else
                nextCaseIndex = 0
            End If

            If (nextCaseIndex <> 0) Then
                currentCaseId = dt.Rows(index)("CaseID").ToString()
                nextCaseId = dt.Rows(index + 1)("CaseID").ToString()
            End If

            If (index = dt.Rows.Count - 1) Then
                currentCaseId = dt.Rows(index)("CaseID").ToString()
                If (currentCaseId <> lastCaseIdSuccessfullyCopied) Then
                    Dim drr As DataRow = dtt.NewRow()
                    drr.BeginEdit()
                    For columnIndex As Integer = 0 To dtt.Columns.Count - 1
                        drr(columnIndex) = dt.Rows(index)(columnIndex)
                    Next
                    drr.EndEdit()
                    dtt.Rows.Add(drr)
                End If
            End If

            If (currentCaseId <> nextCaseId And currentCaseId <> lastCaseIdSuccessfullyCopied and nextCaseId<>String.Empty) Then
                Dim drr As DataRow = dtt.NewRow()
                drr.BeginEdit()
                For columnIndex As Integer = 0 To dtt.Columns.Count - 1
                    drr(columnIndex) = dt.Rows(index)(columnIndex)
                Next
                drr.EndEdit()
                dtt.Rows.Add(drr)
                lastCaseIdSuccessfullyCopied = currentCaseId
            End If
        Next
        Return dtt
    End Function

    Public Function FilterTaskRowsAndReturnDistinctValues(ByVal dt As DataTable) As DataTable
        Dim dtt As DataTable = dt.Clone()
        Dim currentEventId As String = String.Empty
        Dim nextEventId As String = String.Empty
        Dim lastEventIdSuccessfullyCopied As String = String.Empty
        Dim currentEventIndex As Integer
        Dim nextEventIndex As Integer
        For index As Integer = 0 To dt.Rows.Count - 1
            currentEventIndex = index
            If (index < dt.Rows.Count - 1) Then
                nextEventIndex = index + 1
            Else
                nextEventIndex = 0
            End If

            If (nextEventIndex <> 0) Then
                currentEventId = dt.Rows(index)("Event_ID").ToString()
                nextEventId = dt.Rows(index + 1)("Event_ID").ToString()
            End If

            If (index = dt.Rows.Count - 1) Then
                currentEventId = dt.Rows(index)("Event_ID").ToString()
                If (currentEventId <> lastEventIdSuccessfullyCopied) Then
                    Dim drr As DataRow = dtt.NewRow()
                    drr.BeginEdit()
                    For columnIndex As Integer = 0 To dtt.Columns.Count - 1
                        drr(columnIndex) = dt.Rows(index)(columnIndex)
                    Next
                    drr.EndEdit()
                    dtt.Rows.Add(drr)
                End If
            End If

            If (currentEventId <> nextEventId And currentEventId <> lastEventIdSuccessfullyCopied And nextEventId <> String.Empty) Then
                Dim drr As DataRow = dtt.NewRow()
                drr.BeginEdit()
                For columnIndex As Integer = 0 To dtt.Columns.Count - 1
                    drr(columnIndex) = dt.Rows(index)(columnIndex)
                Next
                drr.EndEdit()
                dtt.Rows.Add(drr)
                lastEventIdSuccessfullyCopied = currentEventId
            End If
        Next
        Return dtt
    End Function

#Region "SQL"

    Private Function EventList(ByVal ConId As Integer, ByVal ViewTo As DateTime) As String

        Dim SQL As New StringBuilder

        With SQL

            '.Append("SELECT Case Event_VIP When 0 then D_Event.Event_Description When 1 then 'URGENT: ' +D_Event.Event_Description end as Description, Convert(varchar(10), Event_DTScheduled, 3) as SchDT")
            .Append("SELECT distinct(D_Event.Event_ID ) , Case Event_VIP When 0 then D_Event.Event_Description When 1 then 'URGENT: ' +D_Event.Event_Description end as Task, Convert(varchar(10), Event_DTScheduled, 3) as Scheduled")

            'Case select to pull out context sensitive event linking (i.e. to company, person or case dependant on the linktype value)
            .Append(" , isnull(CASE event_linktype ")
            .Append(" WHEN 1 THEN 'Case ' + cast(D_event.event_linkID AS varchar) + ' (' + product_name + ' for ' + isnull(d_company_case.company_name,'') + ' ' +  isnull(D_Person_Candidate.Person_Fname + ' ' + D_Person_Candidate.Person_Lname,'No Candidate') + ')' ")
            .Append("WHEN 2 THEN D_Person.Person_FName + ' ' + D_Person.Person_LName + isnull(d_company_person.company_name,'')")
            .Append(" WHEN 3 THEN D_Company.Company_Name ")
            .Append(" WHEN 4 THEN 'User Task' ")
            .Append(" ELSE 'Unlinked' END ,'Link not found') ")
            .Append(" AS 'For', Replace(Replace(Replace(Cast(Event_Message as VarChar(50)), CHAR(10), '  '), CHAR(13), '  '), CHAR(9), '  ') as Message")
            .Append(", Event_LinkID, Event_LinkType,")  ' replacing new paragraph marks with spaces
            '.Append(" AS EventLink, Cast(Event_Message as VarChar(50)) as Message, Event_LinkID, Event_LinkType")
            .Append("D_PhoneNumber.PhoneNumber_Number  ,(D_Person_Candidate.Person_FName + ' '+ D_Person_Candidate.Person_LName) as 'Customer Name' ,")
            .Append("Event_DTScheduled, Event_VIP ")
            'From clauses
            .Append(" FROM D_Person D_Person_Candidate RIGHT OUTER JOIN")
            .Append(" D_Company D_Company_Case RIGHT OUTER JOIN")
            .Append(" D_Case ON D_Company_Case.Company_ID = D_Case.Case_CompanyID ON")
            .Append(" D_Person_Candidate.Person_ID = D_Case.Case_CandidateID LEFT OUTER JOIN")
            .Append(" L_Products ON D_Case.Case_ProductID = L_Products.Product_ID RIGHT OUTER JOIN")
            .Append(" D_Event LEFT OUTER JOIN")
            .Append(" D_Person LEFT OUTER JOIN")
            .Append(" D_Company D_Company_Person ON D_Person.Person_CompanyID = D_Company_Person.Company_ID ON")
            .Append(" D_Event.Event_LinkID = D_Person.Person_ID ON D_Case.Case_ID = D_Event.Event_LinkID LEFT OUTER JOIN")
            .Append(" D_Company ON D_Event.Event_LinkID = D_Company.Company_ID")
            .Append(" join D_PhoneNumber on D_PhoneNumber.PhoneNumber_PersonID =D_Person_Candidate.Person_ID")
            'VB CODE DEFINITION Where clause uses consultant ID and date to view from
            .Append(" WHERE (D_Event.Event_Category = 2) ")
            .Append(" AND (D_Event.Event_ScheduledFor = " & ConId & ") ")
            .Append(" AND (D_Event.Event_DTScheduled < CONVERT(DATETIME,'" & CStr(Format(ViewTo, "dd-MMM-yyyy")) & " 23:59:59', 102))")

            'Order By Clause
            .Append(" ORDER BY Event_VIP Desc, Event_DTScheduled")

        End With

        Return SQL.ToString


    End Function


#End Region

    Public Function SQL_Caselist() As String

        Dim StrModule As String

        Dim objDR As DataRow = Nothing
        StrModule = "Form_Fm_MainMenu.SQL_CaseList"

        Dim Gbl_Int_ConID As Integer = CommonDataFunctions.GetLoggedOnConsultantID
        Dim intFormLayout As Integer = 1
        'Dim viewvalue As String = drpView.Text
        'If viewvalue <> String.Empty Then
        '    intFormLayout = Convert.ToInt32(viewvalue)
        'End If
        Try
            ' Dim IntColumn As Integer
            Dim StrSQL As String = String.Empty, objDT As DataTable, IntMenu As Integer, _
                     ObjBtn As Object = Nothing

            Dim StrSQLSelect As String = String.Empty, StrSQLFrom As String = String.Empty, _
                StrSQLWhere As String = String.Empty, StrSQLOrder As String = String.Empty

            'First get the menu layout for this user.

            StrSQL = "Select Con_MenuLayout1, Con_MenuLayout2, Con_MenuLayout3 from L_Consultant where Con_ID = " & Gbl_Int_ConID
            'objDT = CommonDataFunctions.GetSQLDatatable(StrSQL)

            'If objDT.Rows.Count = 0 Then
            '    'Use system default (1)
            '    IntMenu = 1
            'Else
            '    objDR = objDT.Rows(0)
            '    Select Case intFormLayout
            '        Case 1
            '            IntMenu = objDR("Con_MenuLayout1")

            '        Case 2
            '            IntMenu = objDR("Con_MenuLayout2")
            '            If IntMenu = 0 Then
            '                Call MsgBox("No second menu defined, changing to default")
            '                'Me.frm_MenuLayout = 1
            '                IntMenu = 1
            '            End If

            '        Case 3
            '            IntMenu = objDR("Con_MenuLayout3")
            '            If IntMenu = 0 Then
            '                Call MsgBox("No third menu defined, changing to default")
            '                'Me.frm_MenuLayout = 1
            '                IntMenu = 1
            '            End If

            '        Case Else
            '            IntMenu = objDR("Con_MenuLayout1")

            '    End Select

            'End If

            'Build the basic From clause by suming the basic table requirements

            'StrSQL = "SELECT SUM(I_MenuOption.MenuOption_TCompany) AS Comp, SUM(I_MenuOption.MenuOption_TPersonCandidate) AS Cand, "
            'StrSQL = StrSQL & " SUM(I_MenuOption.MenuOption_TPersonContact) AS Cont, SUM(I_MenuOption.MenuOption_TPersonPartner) AS Part"
            'StrSQL = StrSQL & " , SUM(I_MenuOption.MenuOption_TEvent) AS Event"
            'StrSQL = StrSQL & " , SUM(I_MenuOption.MenuOption_TCaseFinance) AS CaseFinance"
            'StrSQL = StrSQL & " FROM D_MenuLink LEFT OUTER JOIN"
            'StrSQL = StrSQL & " I_MenuOption ON D_MenuLink.MenuLink_ItemID = I_MenuOption.MenuOption_ID"
            'StrSQL = StrSQL & " WHERE (D_MenuLink.MenuLink_LayoutID = " & IntMenu & ")"
            'StrSQL = StrSQL & " GROUP BY D_MenuLink.MenuLink_LayoutID"

            'objDT = CommonDataFunctions.GetSQLDatatable(StrSQL)

            'If objDT.Rows.Count = 0 Then
            '    Call MsgBox("Problem reading Menu Layout, please speak to IT", , "Error")
            '    Me.grdCases.ItemsSource = Nothing
            '    Me.grdCases.Rebind()
            '    'Return String.Empty
            '    'Exit Function
            'End If

            'objDR = objDT.Rows(0)
            StrSQLSelect = "Select distinct D_Case.Case_ID as 'CaseId',D_Person_Candidate.Person_FName as 'Candidate' , L_CaseSgage.CaseStage_Title as 'Status',D_Event_Case.NextTask as 'Next Sch Task', "
            StrSQLSelect = StrSQLSelect & "L_Products .Product_Name as 'Product',D_Person_Candidate.Person_Jobtitle as 'Cand JobTitle' , L_Nationality.Country_Nationality as 'Nationality' , "
            StrSQLSelect = StrSQLSelect & "L_Residence.Country_Name as 'Resident' ,Phone.PhoneNumber_Number as 'Cand Phone' "

            StrSQLFrom = "From D_Case left outer join L_Products on D_Case.Case_ProductID = L_Products .Product_ID  "

            'If objDR("comp") > 0 Then
            StrSQLFrom = StrSQLFrom & " Left Outer Join D_Company on D_Case.Case_CompanyID = D_Company.Company_ID"
            'End If

            'If objDR("part") > 0 Then
            'Adds in Candidate automaticaly
            StrSQLFrom = StrSQLFrom & " LEFT OUTER JOIN"
            StrSQLFrom = StrSQLFrom & " D_Person D_Person_Candidate ON D_Case.Case_CandidateID = D_Person_Candidate.Person_ID LEFT OUTER JOIN"
            StrSQLFrom = StrSQLFrom & " D_Dependants LEFT OUTER JOIN"
            StrSQLFrom = StrSQLFrom & " D_Person D_Person_Partner ON D_Dependants.Dependant_ChildID = D_Person_Partner.Person_ID ON"
            StrSQLFrom = StrSQLFrom & " D_Person_Candidate.Person_ID = D_Dependants.Dependant_ParentID"
            'Else
            'If objDR("cand") > 0 Then
            '    StrSQLFrom = StrSQLFrom & " Left Outer Join D_Person D_Person_Candidate on D_Case.Case_CandidateID = D_Person_Candidate.Person_ID"
            'End If
            'End If

            StrSQLFrom = StrSQLFrom & " left outer join L_CaseStages L_CaseSgage on D_Case.Case_StatusID =L_CaseSgage.CaseStage_Number "
            StrSQLFrom = StrSQLFrom & " left outer join L_Country L_Nationality on  D_Person_Candidate .Person_NatID = L_Nationality .Country_ID "
            StrSQLFrom = StrSQLFrom & " left outer join L_Country L_Residence on D_Person_Candidate .Person_ResidentID = L_Residence .Country_ID "
            'If objDR("cont") > 0 Then
            StrSQLFrom = StrSQLFrom & " Left Outer Join D_Person D_Person_Contact on D_Case.Case_ContactID = D_Person_Contact.Person_ID"
            'End If
            StrSQLFrom = StrSQLFrom & " Left Outer Join  D_PhoneNumber  as Phone on Phone.PhoneNumber_PersonID = D_Person_Candidate .Person_ID "
            'If objDR("event") > 0 Then
            StrSQLFrom = StrSQLFrom & " Left Outer Join ("

            StrSQLFrom = StrSQLFrom & " SELECT     "
            StrSQLFrom = StrSQLFrom & " Event_LinkID,"
            StrSQLFrom = StrSQLFrom & " convert(varchar(12),max(Event_DTEntered),103) as LastEvent,"
            StrSQLFrom = StrSQLFrom & " convert(varchar(12),min(case Event_Category when 2 then Event_DTScheduled else null end),103) as NextTask,"
            StrSQLFrom = StrSQLFrom & " convert(varchar(12),max(case Event_Category when 3 then Event_DTCompleted else null end),103) as LastComp,"
            StrSQLFrom = StrSQLFrom & " count(Event_ID) as TotalEvents,"
            StrSQLFrom = StrSQLFrom & " sum(Case Event_Category when 2 then 1 when 3 then 1 else 0 end) as TotalTasks,"
            StrSQLFrom = StrSQLFrom & " Sum(Case Event_Category when 2 then 1 else 0 end) as TotalSched,"
            StrSQLFrom = StrSQLFrom & " Sum(Case Event_Category when 3 then 1 else 0 end) as TotalComp,"
            StrSQLFrom = StrSQLFrom & " sum( Case When Event_Category = 2 AND Event_DTScheduled < getdate() then 1 else 0 end) as TotalOS"

            StrSQLFrom = StrSQLFrom & " FROM D_Event"
            StrSQLFrom = StrSQLFrom & " WHERE (Event_LinkType = 1)"
            StrSQLFrom = StrSQLFrom & " Group By Event_LinkID"

            StrSQLFrom = StrSQLFrom & ") D_Event_Case on D_Case.Case_ID = D_Event_Case.Event_LinkID"
            ' End If

            'If objDR("CaseFinance") > 0 Then
            StrSQLFrom = StrSQLFrom & " Left Outer Join V_Case on D_Case.Case_ID = V_Case.Case_ID"
            'End If



            'Get all the layout items to build the select clause, the rest of the from clause and label the columns

            'StrSQL = "SELECT D_MenuLink.MenuLink_Column, I_MenuOption.MenuOption_ColumnTitle"
            'StrSQL = StrSQL & " ,I_MenuOption.MenuOption_SQLSelect , I_MenuOption.MenuOption_SQLFrom"
            'StrSQL = StrSQL & " FROM D_MenuLink LEFT OUTER JOIN"
            'StrSQL = StrSQL & " I_MenuOption ON D_MenuLink.MenuLink_ItemID = I_MenuOption.MenuOption_ID"
            'StrSQL = StrSQL & " WHERE (D_MenuLink.MenuLink_LayoutID = " & IntMenu & ")"
            'StrSQL = StrSQL & " ORDER BY D_MenuLink.MenuLink_Column"

            'objDT = CommonDataFunctions.GetSQLDatatable(StrSQL)

            'If objDT.Rows.Count > 0 Then
            '    If objDT.Rows.Count < 8 Then
            '        Call MsgBox("Incomplete Menu Layout, please speak to IT", , "Error")
            '        Me.grdCases.ItemsSource = Nothing
            '        Me.grdCases.Rebind()
            '        'Return String.Empty
            '        'Exit Function
            '    End If
            'Else
            '    Call MsgBox("Empty Menu Layout, please speak to IT", , "Error")
            '    Me.grdCases.ItemsSource = Nothing
            '    Me.grdCases.Rebind()
            '    'Return String.Empty
            '    'Exit Function
            'End If

            'Build select clause
            
            'ReDim StrFieldNames(0 To objDT.Rows.Count + 1)
            'Dim intPtr As Integer = 1

            'For Each objDR In objDT.Rows
            '    'StrSQLSelect = StrSQLSelect & ", " & IIf(objDR("MenuOption_SQLSelect") Is DBNull.Value, True, objDR("MenuOption_SQLSelect")) & " as Col_" & objDR("Menuoption_Column")
            '    StrSQLSelect = StrSQLSelect & ", " & IIf(objDR("MenuOption_SQLSelect") Is DBNull.Value, True, objDR("MenuOption_SQLSelect")) & " as '" & objDR("Menuoption_ColumnTitle") & "' " 'krishan kumar k
            '    StrSQLFrom = StrSQLFrom & " " & objDR("Menuoption_sqlfrom")
            '    StrFieldNames(intPtr) = objDR("Menuoption_ColumnTitle")
            '    intPtr += 1
            'Next


            If radViewPreSale.IsChecked = True Then
                'Pre Sale cases
                StrSQLWhere = "WHERE  (D_Case.Case_StatusID < 4) and (D_Case.Case_StatusID NOT IN(17,18))"
            ElseIf radViewInitiated.IsChecked = True Then
                'Initiated Cases
                StrSQLWhere = "WHERE (D_Case.Case_StatusID BETWEEN 4 AND 10) and (D_Case.Case_StatusID NOT IN(17,18))"
            ElseIf radViewAll.IsChecked = True Then
                'All cases
                StrSQLWhere = "WHERE (D_Case.Case_StatusID < 1000) and (D_Case.Case_StatusID NOT IN(17,18))"
            End If


            'If Not Me.Chk_OnHold Then
            '   StrSQLWhere = StrSQLWhere & " AND D_Case.Case_ActiveStatus = 0"
            'End IF
            Dim singleObject As Singleton = Singleton.Instance
            Dim salesConsultantId As String = singleObject.CurrentConId
            If (Me.drpCons.SelectedValue <> Nothing) Then
                If (Me.drpCons.SelectedValue.ToString <> String.Empty) Then
                    salesConsultantId = Me.drpCons.SelectedValue
                End If
            End If
            If (radHoldExclude.IsLoaded) Then
                If radHoldExclude.IsChecked = True Then
                    'Exclude
                    StrSQLWhere = StrSQLWhere & " AND D_Case.Case_ActiveStatus = 0"
                ElseIf radHoldInclude.IsChecked = True Then
                    'Include
                    'No restriction
                ElseIf radHoldOnly.IsChecked = True Then
                    'Show Only
                    StrSQLWhere = StrSQLWhere & " AND D_Case.Case_ActiveStatus = 1"
                End If
            End If
            
            If radRoleSales.IsLoaded = True Then
                If radRoleSales.IsChecked = True Then
                    'Sales Con
                    StrSQLWhere = StrSQLWhere & " AND (D_Case.Case_ConSaleID = " & salesConsultantId & ")"
                ElseIf radRoleCW.IsChecked = True Then
                    'Caseworker
                    StrSQLWhere = StrSQLWhere & " AND (D_Case.Case_ConCWID = " & salesConsultantId & ")"
                ElseIf radRoleCaseCoordinator.IsChecked = True Then
                    ' Case Coordinator
                    StrSQLWhere = StrSQLWhere & " AND (D_Case.Case_CoordinatorID = " & salesConsultantId & ")"
                ElseIf radRoleEither.IsChecked = True Then
                    'Either
                    StrSQLWhere = StrSQLWhere & " AND ((D_Case.Case_ConSaleID = " & salesConsultantId & ") OR (D_Case.Case_ConCWID = " & salesConsultantId & ") or D_Case.Case_CoordinatorID = " & salesConsultantId & ")"
                End If
            End If

            StrSQLOrder = ""

            StrSQL = StrSQLSelect & " " & StrSQLFrom & " " & StrSQLWhere & " " & StrSQLOrder

            Return (StrSQL)



        Catch ex As Exception
            Return String.Empty
            CommonFuncs.ErrorHandler(ex, "frmMainForm.SQL_CASELIST")
            'Ret = MsgBox("An error has occured, please contact the IT dept and quote the following code: " & IntErr, , "Error")
        Finally

        End Try
        ' End Error handling block.

    End Function

    Private Sub LoadCurrentValues()
        Try
            Dim _ConBranchID As Integer = CommonDataFunctions.GetLoggedOnConsultantBranchID
            Dim singleObject As Singleton = Singleton.Instance
            Dim _ConDeptID As Integer = CommonDataFunctions.GetLoggedOnConsultantDeptID(singleObject.CurrentConName.Trim)

            With Me.drpBranch
                .ItemsSource = Nothing
                .SelectedValuePath = "Branch_ID"
                .DisplayMemberPath = "Branch_Name"
                .ItemsSource = CType(CommonDataFunctions.BranchList, IListSource).GetList
                .SelectedValue = _ConBranchID
            End With

            With Me.drpDepts
                .ItemsSource = Nothing
                .SelectedValuePath = "Department_ID"
                .DisplayMemberPath = "Department_Name"
                .ItemsSource = CType(CommonDataFunctions.DepartmentList(Me.drpBranch.SelectedValue), IListSource).GetList
                .SelectedValue = _ConDeptID
            End With
            With Me.drpCons
                .ItemsSource = Nothing
                .SelectedValuePath = "con_id"
                .DisplayMemberPath = "con_name"
                .ItemsSource = CType(CommonDataFunctions.ConsultantList(True, drpDepts.SelectedValue), IListSource).GetList
            End With

        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmCRMMainForm -LoadCurrentValues")
        End Try

    End Sub
    Private Sub drpBranch_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles drpBranch.SelectionChanged

        Try
            If Me.currentConName = "once" Then
                Me.drpDepts.ItemsSource = Nothing
                'LoadCurrentValues()
                Exit Sub
            End If
            With Me.drpDepts
                .ItemsSource = CType(CommonDataFunctions.DepartmentList(Me.drpBranch.SelectedValue), IListSource).GetList
                .SelectedValuePath = "Department_ID"
                .SelectedValuePath = "Department_Name"
                .SelectedIndex = -1
                drpDepts_SelectionChanged(sender, e)
            End With
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmMainForm.drpBranch_SelectedIndexChanged") ', False)
        Finally
            Me.currentConName = String.Empty
        End Try
    End Sub

    Private Sub btnAllocation_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAllocation.Click
        Try
            'MainDisplay.Focus()
            'GlobalCRM.CurrentBranchId = CommonFunc.GetBranchID(GlobalCRM.CurrentConID)
            'frmUnassignedCases.MdiParent = frmMDIMain
            'Dim UnassignedCasesForm As New frmUnassignedCases()
            '            UnassignedCasesForm.ShowDialog() -- sumathivinayak S
            RaiseEvent ShowDynamicTab("unassigned")
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmMainForm.btnAllocation_Click", False)
        End Try
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        'Dim f1 As New frmAdminEmailTemplates
        Dim f1 As New frmAdminCustomizeCRMView
        f1.ShowDialog()

    End Sub


    Private Sub grdCases_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles grdCases.MouseDoubleClick
        Dim currentPosition As Point = e.GetPosition(Me.grdCases)
        Dim percentageWidth As Double = currentPosition.X / grdCases.ActualWidth * 100
        Dim percentageHeight As Double = currentPosition.Y / grdCases.ActualHeight * 100
        If percentageWidth > 98.2086406743941 Or percentageHeight < 24.480060195635829 Then
            Exit Sub
        End If
        'Dim group1 As Telerik.Windows.Controls.GridView.GridViewGroupRow
        Dim currentRow As DataRow = grdCases.SelectedItem
        Dim progressBar As frmProgressBar = Nothing
        ' open frmMainDisplay for selected event
        Try
            progressBar = New frmProgressBar()
            progressBar.TextToDisplay = "Dear " & GlobalCRM.CurrentConName & ", please wait while CRM loads the Case Id :" & currentRow(0).ToString()
            progressBar.Show()

            'group1 = New Telerik.Windows.Controls.GridView.GridViewGroupRow

            'If grdCases.CurrentItem.ToString = group1.ToString Then
            If currentRow Is Nothing Then

                ' CommonFuncs.DisplayMessage("Please Double click on Item level. Double clicking on Group Item is not valid", CustomDialogIcons.Information, "Error")

                Exit Sub
            End If

            ' Dim currentRow As DataRow = grdCases.CurrentItem

            GlobalCRM.CurrentCaseID = currentRow(0)

            ' log event and userhistory records 
            CommonDataFunctions.GblFunc_Goto_ID(GlobalCRM.CurrentCaseID, CommonFuncs.DBIdTypes.CaseID)

            'frmMainDisplay.MdiParent = frmMDIMain
            'Dim MainFormDisplay As New frmMainDisplay()

            'MainFormDisplay.ShowDialog()

            frmCRMMainDisplay.loadTabCases = False
            frmCRMMainDisplay.loadTabAccounts = False
            frmCRMMainDisplay.loadTabPeople = False
            frmCRMMainDisplay.loadTabCompany = False
            frmCRMMainDisplay.loadTabDocs = False
            frmCRMMainDisplay.loadTabEvent = False

            RaiseEvent ShowDynamicTab("maindisplay")
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmMainForm.grdCases_MouseDoubleClick", False)
        Finally
            '            group1 = Nothing
            currentRow = Nothing
            progressBar.Close()
        End Try
    End Sub

    Private Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnSearch.Click
        Try
            'jh()
            Dim SearchForm As New frmSearch()
            SearchForm.ShowDialog()
            'If GlobalCRM.CurrentCaseID > 0 Or GlobalCRM.CurrentCandidateID > 0 Or GlobalCRM.CurrentCompanyID Then
            If SearchForm.blnLoadMainform = True Then
                RaiseEvent ShowDynamicTab("maindisplay")
            End If
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmMainForm.btnSearch_Click", False)
        End Try
    End Sub

    Private Sub btnRefresh_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnRefresh.Click
        Try
            'If Letters.UploadFileToHttpOrFtp("", "", True, "sumathiv", "sumchu123") = "True" Then
            '    Dim abc As Integer = 0
            'End If
            Me.RefreshLists()
            refreshGrid()
            RefreshOutStandingTaksForLoggedConsultant()
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmMainForm.btnRefresh_Click", False)
        End Try

    End Sub

    Private Sub btnHistory_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnHistory.Click
        Dim history As frmHistory
        Try
            history = New frmHistory

            history.ShowDialog()
            If history.blnLoadMainform = True Then
                'If Not GlobalCRM.CurrentCaseID = 0 Or Not GlobalCRM.CurrentCompanyID = 0 Or Not GlobalCRM.CurrentCandidateID = 0 Then
                RaiseEvent ShowDynamicTab("maindisplay")
            End If

        Catch ex As Exception
        Finally
            history = Nothing
        End Try
    End Sub

    Private Sub btnBrowseTasks_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnBrowseTasks.Click
        Dim frmBrowseTasks As New frmBrowseTasks
        Try
            frmBrowseTasks.ShowDialog()
            If GlobalCRM.CurrentCaseID > 0 Then
                RaiseEvent ShowDynamicTab("maindisplay")
            End If
        Catch ex As Exception
            'CommonFunc.ErrorHandler(ex, "frmMainForm.btnBrowse_Click", False)
        Finally
            frmBrowseTasks = Nothing
        End Try
    End Sub

    Public Sub UpdateView(ByVal Sender As Object, ByVal e As System.EventArgs)
        If firstLoad = False Then
            'Exit Sub
        End If
        Dim singleObject As Singleton = Singleton.Instance
        Try
            If singleObject.CurrentConId > 0 Then
                Dim sql As String = Me.SQL_Caselist '(Me.StatusCaseStatus, Me.StatusConRole, OnHold.Exclude)
                'objDTGrid = DB.GetSQLDataTable(Me.CaseListSQL(Me.StatusCaseStatus, Me.StatusConRole, OnHold.Exclude))
                blnForceLoadGrid = True
                LoadGrid()
                Me.GetColumns()
            End If
        Catch ex As Exception
            ' CommonFunc.ErrorHandler(ex, "frmMainForm.UpdateView", False)
        End Try

    End Sub

    Private Sub btnDismissTask_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnDismissTask.Click
        Dim frmCompleteEvent As New frmCompleteEvent
        Try
            If Me.lvwEventsOutstanding.SelectedItems.Count = 0 Then
                CommonFuncs.DisplayMessage("Please select a task first", CustomDialogIcons.Information, "")
                frmCompleteEvent = Nothing
                Exit Sub
            End If
            If Me.lvwEventsOutstanding.SelectedItem.itemarray(6).ToString = 1 Then
                frmCompleteEvent.caseid = Me.lvwEventsOutstanding.SelectedItem.itemarray(0).ToString
                GlobalCRM.CurrentCaseID = Me.lvwEventsOutstanding.SelectedItem.itemarray(5).ToString
            End If
            frmCompleteEvent.EventId = Me.lvwEventsOutstanding.SelectedItem.itemarray(0).ToString
            frmCompleteEvent.ShowDialog()
            Me.RefreshLists()

            If frmCompleteEvent.RepeatEvent Then

                ' xxx you need to add code to ask for a repeat event

            End If
        Catch ex As Exception
        Finally
            frmCompleteEvent = Nothing
        End Try
    End Sub


    Private Sub lvwEventsOutstanding_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
        Try
            If Me.lvwEventsOutstanding.SelectedItems.Count = 0 Then
                Exit Sub
            End If

            ' find out what task is associated with, eg case, company, person or consultant
            Dim intLinkType As Integer = Me.lvwEventsOutstanding.SelectedItem.row.itemarray(6).ToString

            If intLinkType = 0 Then
                ' do nothing
                Exit Sub
            ElseIf intLinkType = 4 Then
                Dim peer As ButtonAutomationPeer = New ButtonAutomationPeer(btnDismissTask)
                Dim invokeProv As IInvokeProvider = peer.GetPattern(PatternInterface.Invoke) ' as IInvokeProvider
                invokeProv.Invoke()
                Exit Sub
            Else
                ' open frmMainDisplay
                If intLinkType = 1 Then
                    GlobalCRM.CurrentCaseID = Me.lvwEventsOutstanding.SelectedItem.row.itemarray(5).ToString
                    CommonDataFunctions.GblFunc_Goto_ID(GlobalCRM.CurrentCaseID, CommonDataFunctions.DBIdTypes.CaseID)
                ElseIf intLinkType = 2 Then
                    GlobalCRM.CurrentCandidateID = Me.lvwEventsOutstanding.SelectedItem.row.itemarray(5).ToString
                    CommonDataFunctions.GblFunc_Goto_ID(GlobalCRM.CurrentCaseID, CommonDataFunctions.DBIdTypes.PersonID)
                ElseIf intLinkType = 3 Then
                    GlobalCRM.CurrentCompanyID = Me.lvwEventsOutstanding.SelectedItem.row.itemarray(5).ToString
                    CommonDataFunctions.GblFunc_Goto_ID(GlobalCRM.CurrentCaseID, CommonDataFunctions.DBIdTypes.CompanyID)
                End If
                'frmMainDisplay.MdiParent = frmMDIMain
                'frmMainDisplay.Show()

                RaiseEvent ShowDisplayForm("maindisplay")
            End If
        Catch ex As Exception
            'CommonFunc.ErrorHandler(ex, "frmMainForm.lvwEventsOutstanding_DoubleClick", False)
        End Try
    End Sub

    Private Sub btnAdmin_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAdmin.Click
        Dim frmAdminHome As New frmAdminHome
        Try
            frmAdminHome.ShowDialog()
        Catch ex As Exception
            'CommonFunc.ErrorHandler(ex, "frmMainForm.btnHistory_Click", False)
        Finally
            frmAdminHome = Nothing
        End Try
    End Sub

    Private Sub ViewChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles radViewAll.Checked, radViewInitiated.Checked, radViewPreSale.Checked
        Try
            ' respond to View radio button selection
            If GlobalCRM.CurrentConID > 0 Then
                If firstLoad = False Then
                    'Exit Sub
                End If


                Select Case CType(CType(sender, RadioButton).Tag, CaseStatus)
                    Case CaseStatus.All
                        '  objDTGrid = CommonDataFunctions.GetSQLDatatable(Me.SQL_Caselist(CaseStatus.All, Me.StatusConRole, Me.StatusOnHold))
                    Case CaseStatus.Initiated
                        ' objDTGrid = CommonDataFunctions.GetSQLDatatable(Me.SQL_Caselist(CaseStatus.Initiated, Me.StatusConRole, Me.StatusOnHold))
                    Case CaseStatus.PreSale
                        'objDTGrid = CommonDataFunctions.GetSQLDatatable(Me.SQL_Caselist(CaseStatus.PreSale, Me.StatusConRole, Me.StatusOnHold))
                End Select
                blnForceLoadGrid = True
                LoadGrid()
                'Me.grdCases.ItemsSource = objDTGrid
                'Me.GetColumns()
            End If
        Catch ex As Exception
            'CommonFunc.ErrorHandler(ex, "frmMainForm.ViewChanged", False)
        End Try

    End Sub

    Private Sub RoleChanged(ByVal Sender As Object, ByVal e As System.EventArgs) Handles radRoleCW.Checked, radRoleEither.Checked, radRoleSales.Checked, radRoleCaseCoordinator.Checked
        If firstLoad = False Then
            ' Exit Sub
        End If
        ' respond to consultants Role radio button selection
        Try
            Select Case CType(CType(Sender, RadioButton).Tag, ConRole)
                Case ConRole.CaseWorker
                    'objDTGrid = DB.GetSQLDataTable(Me.CaseListSQL(Me.StatusCaseStatus, ConRole.CaseWorker, Me.StatusOnHold))
                Case ConRole.Either
                    'objDTGrid = DB.GetSQLDataTable(Me.CaseListSQL(Me.StatusCaseStatus, ConRole.Either, Me.StatusOnHold))
                Case ConRole.SalesCon
                    'objDTGrid = DB.GetSQLDataTable(Me.CaseListSQL(Me.StatusCaseStatus, ConRole.SalesCon, Me.StatusOnHold))
                Case ConRole.CaseCoordinator
                    'objDTGrid = DB.GetSQLDataTable(Me.CaseListSQL(Me.StatusCaseStatus, ConRole.CaseCoordinator, Me.StatusOnHold))
            End Select

            'Me.grdCases.DataSource = objDTGrid
            'Me.GetColumns()
            blnForceLoadGrid = True
            LoadGrid()
        Catch ex As Exception
            ' CommonFunc.ErrorHandler(ex, "frmMainForm.RoleChanged", False)
        End Try
    End Sub

    Private Sub OnHoldChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles radHoldExclude.Checked, radHoldInclude.Checked, radHoldOnly.Checked
        If firstLoad = False Then
            Exit Sub
        End If
        ' respond to cases On Hold radio button selection
        Try
            Select Case CType(CType(sender, RadioButton).Tag, OnHold)
                Case OnHold.Exclude
                    'objDTGrid = DB.GetSQLDataTable(Me.CaseListSQL(Me.StatusCaseStatus, Me.StatusConRole, OnHold.Exclude))
                Case OnHold.Include
                    'objDTGrid = DB.GetSQLDataTable(Me.CaseListSQL(Me.StatusCaseStatus, Me.StatusConRole, OnHold.Include))
                Case OnHold.Only
                    'objDTGrid = DB.GetSQLDataTable(Me.CaseListSQL(Me.StatusCaseStatus, Me.StatusConRole, OnHold.Only))

            End Select
            'Me.grdCases.DataSource = objDTGrid
            'Me.GetColumns()
            blnForceLoadGrid = True
            LoadGrid()
        Catch ex As Exception
            'CommonFunc.ErrorHandler(ex, "frmMainForm.onHoldChanged", False)
        End Try

    End Sub

    Private Sub lvwEventsOutstanding_MouseDoubleClick1(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles lvwEventsOutstanding.MouseDoubleClick
        Dim progressBar As frmProgressBar = Nothing
        ' open frmMainDisplay for selected event
        Try
            progressBar = New frmProgressBar()
            progressBar.TextToDisplay = "Dear " & GlobalCRM.CurrentConName & ", please wait while CRM loads the case for the event ....."
            progressBar.Show()

            If Me.lvwEventsOutstanding.SelectedItems.Count = 0 Then
                Exit Sub
            End If

            ' find out what task is associated with, eg case, company, person or consultant
            Dim intLinkType As Integer = Me.lvwEventsOutstanding.SelectedItem.itemarray(6).ToString

            If intLinkType = 0 Then
                ' do nothing
                Exit Sub
            ElseIf intLinkType = 4 Then
                ' open dismiss task form
                btnDismissTask_Click(sender, e)
                'btnDismissTask.PerformClick()
                Exit Sub
            Else
                ' open frmMainDisplay
                If intLinkType = 1 Then
                    GlobalCRM.CurrentCaseID = Me.lvwEventsOutstanding.SelectedItem.itemarray(5).ToString
                    CommonDataFunctions.GblFunc_Goto_ID(GlobalCRM.CurrentCaseID, CommonDataFunctions.DBIdTypes.CaseID)
                    GlobalCRM.TabSelection = GlobalCRM.enumSelectTab.eCase
                    GlobalCRM.CurrentSearchType = GlobalCRM.enuSearchType.eCase
                ElseIf intLinkType = 2 Then
                    GlobalCRM.CurrentCandidateID = Me.lvwEventsOutstanding.SelectedItem.itemarray(5).ToString
                    CommonDataFunctions.GblFunc_Goto_ID(GlobalCRM.CurrentCaseID, CommonDataFunctions.DBIdTypes.PersonID)
                    GlobalCRM.TabSelection = GlobalCRM.enumSelectTab.ePerson
                    GlobalCRM.CurrentSearchType = GlobalCRM.enuSearchType.ePerson
                ElseIf intLinkType = 3 Then
                    GlobalCRM.CurrentCompanyID = Me.lvwEventsOutstanding.SelectedItem.itemarray(5).ToString
                    CommonDataFunctions.GblFunc_Goto_ID(GlobalCRM.CurrentCaseID, CommonDataFunctions.DBIdTypes.CompanyID)
                    GlobalCRM.TabSelection = GlobalCRM.enumSelectTab.eCompany
                    GlobalCRM.CurrentSearchType = GlobalCRM.enuSearchType.eCompany
                End If
                '                frmMainDisplay.MdiParent = frmMDIMain
                'frmMainDisplay.Show()

                frmCRMMainDisplay.loadTabCases = False
                frmCRMMainDisplay.loadTabAccounts = False
                frmCRMMainDisplay.loadTabPeople = False
                frmCRMMainDisplay.loadTabCompany = False
                frmCRMMainDisplay.loadTabDocs = False
                frmCRMMainDisplay.loadTabEvent = False

                RaiseEvent ShowDynamicTab("maindisplay")
            End If
        Catch ex As Exception
            'CommonFunc.ErrorHandler(ex, "frmMainForm.lvwEventsOutstanding_DoubleClick", False)
        Finally
            progressBar.Close()
        End Try
    End Sub

    Private Sub grdCases_MouseDoubleClick1(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
        Try
            If grdCases.SelectedItems.Count > 0 Then


                GlobalCRM.CurrentCaseID = grdCases.SelectedItem.itemarray(0).ToString

                ' log event and userhistory records 
                CommonDataFunctions.GblFunc_Goto_ID(GlobalCRM.CurrentCaseID, CommonDataFunctions.DBIdTypes.CaseID)

                RaiseEvent ShowDisplayForm("maindisplay")
            End If
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmMainForm.grdCases_MouseDoubleClick", False)
        Finally

        End Try

    End Sub

    Private Sub lvwEventsOutstanding_SelectionChanged(ByVal sender As Object, ByVal e As Telerik.Windows.Controls.SelectionChangeEventArgs) Handles lvwEventsOutstanding.SelectionChanged
        Try

            If Me.lvwEventsOutstanding.SelectedItems.Count > 0 Then
                Me.btnDismissTask.IsEnabled = True

            Else
                Me.btnDismissTask.IsEnabled = False
                Exit Sub
            End If

            Me.txtMessage.Text = CommonDataFunctions.GetEventMessage(Me.lvwEventsOutstanding.SelectedItem.itemarray(0).ToString)
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmMainForm.lvwEventsOutstanding_ItemSelectionChanged", False)
        End Try

    End Sub

    Private Sub btnAddAccount_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddAccount.Click
        Try
            ' reset global variables
            GlobalCRM.ResetGlobalVars()

            ' open appropriate form
            If Me.radAddColdCall.IsChecked Then
                'frmAddAccount.MdiParent = frmMDIMain
                'Dim frmAddAccount As New frmAddAccount
                RaiseEvent ShowDynamicTab("addaccount")
            ElseIf Me.radAddCompany.IsChecked Then
                Dim frmAddNewCompany As New frmAddNewCompany
                frmAddNewCompany.SaveMode = frmAddNewCompany.SaveModes.NewCompany
                frmAddNewCompany.ShowDialog()
                If GlobalCRM.CurrentCompanyID > 0 Then
                    RaiseEvent ShowDynamicTab("maindisplay")
                End If
            ElseIf Me.radAddPerson.IsChecked Then
                Dim frmAddPerson As New frmAddPerson
                frmAddPerson.ShowDialog()
                If GlobalCRM.CurrentCandidateID > 0 Then
                    RaiseEvent ShowDynamicTab("maindisplay")
                End If
            End If
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmMainForm.btnAddAccount_Click", False)
        End Try

    End Sub



    'Private Sub btnAbout_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAbout.Click
    '    Dim frmAbout As New frmAbout
    '    frmAbout.ShowDialog()
    '    frmAbout.ShowInTaskbar = False
    'End Sub

    Private Sub btnAbout_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAbout.Click
        Dim frmabout As New frmAbout
        frmabout.ShowDialog()
        frmabout = Nothing
    End Sub

    Private Sub cmbStyle_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles cmbStyle.SelectionChanged

        If cmbStyle.SelectedIndex <> -1 Then
            Dim item As ComboBoxItem = cmbStyle.Items(cmbStyle.SelectedIndex)
            My.Settings.CurrentTheme = item.Content
            My.Settings.Save()
            GeneralTasks.ChangeTheme(Me)
            Me.cmbStyle.Text = item.Content
        End If

    End Sub

    Private Sub cmbColor_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles cmbColor.SelectionChanged
        If cmbColor.SelectedIndex <> -1 Then
            Dim item As DataRowView = cmbColor.Items(cmbColor.SelectedIndex)
            My.Settings.CurrentColor = item(0)
            My.Settings.Save()
            GeneralTasks.EnumerateandFill(Me.LogicalChildren)
            'GeneralTasks.ChangeTheme(Me)
        End If
    End Sub

    Private Sub grdCases_RowLoaded(ByVal sender As Object, ByVal e As Telerik.Windows.Controls.GridView.RowLoadedEventArgs) Handles grdCases.RowLoaded
        'Dim gvscore As Object = grdCases.ChildrenOfType(Of GridViewCell)().Where(Function(c) c.Column.UniqueName = "Score").ToList()
        ''Dim gvscore As Object = grdCases.ChildrenOfType(Of GridViewComboBoxEditor)().Where(Function(c) c.Column.UniqueName = "GV_Score").ToList()
        'For Each value As Object In gvscore
        '    Select Case value.Value.ToString
        '        Case "Orange"
        '            value.background = Brushes.Orange
        '        Case "Green"
        '            value.background = Brushes.LightGreen
        '        Case "Red"
        '            value.background = Brushes.Red
        '    End Select
        'Next
    End Sub

    Private Sub frmCRMMainForm_LostFocus(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.LostFocus
        Me.checkLoad = True
        Me.firstLoad = False
    End Sub

    Private Sub ctxGreen_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim tsk As New TasksEvents
        Try
            If grdCases.SelectedItems.Count > 0 Then
                If grdCases.SelectedItems.Count = 1 Then
                    If CommonDataFunctions.UpdateGVScore(grdCases.SelectedItem.item(1).ToString, 3) = True Then
                        tsk.GblFunc_Add_Event("GV Score", "The GV Score has been updated to Green", TasksEvents.EventStatus.SingleEvent, grdCases.SelectedItem.item(1).ToString, 1)
                        'grdCases.SelectedItem.item(0) = "Green"
                        LoadGrid()
                    End If
                End If
            End If
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmMainForm.ctxGreen_Click", False)
        Finally
            tsk = Nothing
        End Try
        
    End Sub

    Private Sub ctxRed_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs)
        '1
        Dim tsk As New TasksEvents
        Try
            If grdCases.SelectedItems.Count > 0 Then
                If grdCases.SelectedItems.Count = 1 Then
                    If CommonDataFunctions.UpdateGVScore(grdCases.SelectedItem.item(1).ToString, 1) = True Then
                        tsk.GblFunc_Add_Event("GV Score", "The GV Score has been updated to Red", TasksEvents.EventStatus.SingleEvent, grdCases.SelectedItem.item(1).ToString, 1)
                        'grdCases.SelectedItem.item(0) = "Red"
                        LoadGrid()
                    End If
                End If
            End If
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmMainForm.ctxRed_Click", False)
        Finally
            tsk = Nothing
        End Try
    End Sub

    Private Sub ctxOrange_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs)
        '2
        Dim tsk As New TasksEvents
        Try
            If grdCases.SelectedItems.Count > 0 Then
                If grdCases.SelectedItems.Count = 1 Then
                    If CommonDataFunctions.UpdateGVScore(grdCases.SelectedItem.item(1).ToString, 2) = True Then
                        tsk.GblFunc_Add_Event("GV Score", "The GV Score has been updated to Orange", TasksEvents.EventStatus.SingleEvent, grdCases.SelectedItem.item(1).ToString, 1)
                        'grdCases.SelectedItem.item(0) = "Orange"
                        'Dim gvscore As Object = grdCases.ChildrenOfType(Of GridViewCell)().Where(Function(c) c.Column.UniqueName = "GV_Score" And c.Value.ToString = "Orange").ToList()
                        'grdCases.SelectedItem.item(0).background = Brushes.LightYellow
                        LoadGrid()
                    End If
                End If
            End If
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmMainForm.ctxOrange_Click", False)
        Finally
            tsk = Nothing
        End Try
    End Sub

    Private Sub frmCRMMainForm_TargetUpdated(ByVal sender As Object, ByVal e As System.Windows.Data.DataTransferEventArgs) Handles Me.TargetUpdated

    End Sub

   
End Class
